uid0 =  [0 0 1 0 1 1 0 1];
uid1 = [0 0 0 1 1 1 1 1];
uid2 = [1 1 1 1 0 1 1 0];
uid3 = [0 1 1 1 1 0 1 0];
bcc = [1 0 1 1 1 1 1 0];
% data is already in LSByte order (uid0 .. uid3, bcc)

% parity bits
p0 = 1 - mod(sum(uid0),2);
p1 = 1 - mod(sum(uid1),2);
p2 = 1 - mod(sum(uid2),2);
p3 = 1 - mod(sum(uid3),2);
pbcc = 1 - mod(sum(bcc),2);

% add data in least significant byte, least significant bit first
% interleave parity bits
data = [fliplr(uid0), p0, fliplr(uid1), p1, fliplr(uid2), p2, fliplr(uid3), p3, fliplr(bcc), pbcc];

[signal, t] = ManchesterSignal(data);

subplot(2,1,1);
plot(t,signal);
ylim ([-0.05 1.05]);

% Corrupt first part of signal
offset = round(0.4 * 900);
t = t(offset:end) - t(offset);
signal = signal(offset:end);

subplot(2,1,2);
plot(t,signal);
ylim ([-0.05 1.05]);

periods = ManchesterPeriod(signal, t);
newdata = ManchesterDecode(periods);

disp(['Cut was ' int2str(offset)]);
if isequal(data, newdata)
    disp('Data matches');
else
    disp('Data mismatch');
    disp(mat2str(data));
    disp(strrep(mat2str(padarray(newdata,[0 size(data,2) - size(newdata,2)],-1,'pre')),'-1',' '));
end

repaireddata = RecoverData(newdata);
sent = [uid0
    uid1
    uid2
    uid3
    bcc];
disp(['Reconstructed signal equals transmitted data: ' num2str(isequal(repaireddata, sent))]);


return;
for i=1:1:9000
    % Corrupt first part of signal
    newt = t(i:end) - t(i);
    newsignal = signal(i:end);
    
    periods = ManchesterPeriod(newsignal, newt);
    newdata = ManchesterDecode(periods);
    
    begin = size(data,2) - size(newdata,2) +1;
    comparedata = data(begin:end);
    if ~isequal(comparedata,newdata)
        if isequal(comparedata, 1 - newdata)
            disp(['Inverted for ' int2str(i) ' time: ' num2str(t(i))]);
        else
            disp(['Corrupt for ' int2str(i) ' time: ' num2str(t(i))]);
%             disp(mat2str(comparedata));
%             disp(mat2str(newdata));
%             disp(mat2str(1 - newdata));
        end
    end
end